import React, { useState, useRef } from 'react';
import { message, Input, Select, Badge } from 'antd';
import debounce  from 'lodash.debounce';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import PlanReviewModel from './components/PlanReviewModel';
import TagCommonComponent from '../System/components/TagCommonComponent';
import { TableListItem, PlanItemParam } from './data.d';
import { planAuditList, planPass, planReject } from './service';


const { Search } = Input;
const { Option } = Select;

const PlanReview: React.FC<{}> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [approvedLoading, handleApprovedLoading] = useState<boolean>(false);
  const [rejectLoading, handleRejectLoading] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [values, setValues] = useState<PlanItemParam>();

  //标签选中监听
  const selectChange = (values:any,form:any) => {
    form.setFieldsValue({"tagIds": values.toString()});
    form.submit();
  }
  
  //通过审核
  const onApproved = async (values:PlanItemParam) => {
    // console.log(values);
    if (values && values.code) {
      handleApprovedLoading(true);
      const code = values.code;
      const obj = new Object;
      obj["auditReason"] = values.auditReason;
      new Promise((resolve, reject) => {
        planPass(code,obj)
          .then((res) => {
            if (res.code === 200) {
              message.success('审核通过');
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
              resolve(true);
            }else {
              message.error(res.message);
              resolve(false);
            }
            handleApprovedLoading(false);
          })
          .catch((error) => {
            message.error('请求失败');
            reject(error);
          });
      });
    };
  }
  //驳回
  const onReject = (values:PlanItemParam) => {
    if (values && values.code) {
      handleRejectLoading(true);
      const code = values.code;
      const obj = new Object;
      obj["auditReason"] = values.auditReason;
      new Promise((resolve, reject) => {
        planReject(code,obj)
          .then((res) => {
            if (res.code === 200) {
              message.success('审核驳回');
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
              resolve(true);
            }else {
              message.error(res.message);
              resolve(false);
            }
            handleRejectLoading(false);
          })
          .catch((error) => {
            message.error('请求失败');
            reject(error);
          });
      });
    };
  }
  const columns: ProColumns<PlanItemParam>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'text',
      hideInSearch: true, 
      width:80,
    },
    {
      title: '计划名称',
      dataIndex: 'name',
      ellipsis: true,
      width:200,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Search
              placeholder="请输入计划名称"
              onSearch={debounce(value=>{form.submit()}, 500)}
              onChange={debounce(value=>{form.submit()}, 500)}
              style={{ width: 200 }}
            />
          );
        }
        return defaultRender(_);
      },
      render:  (_, record) => (
        record.defaultPlan == 0? record.name: (
          <Badge count="默认计划" style={{background:'#1890ff', color:'#fff'}} offset={[30, 0]}><label>{record.name}</label></Badge>)
      ),
      valueType: 'text',
    },
    {
      title: '发布方式',
      dataIndex: 'publishWay',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Select
              showSearch
              optionFilterProp="children"
              style={{ width: 200 }}
              placeholder="请选择"
              onChange={(value) => form.submit()}
            >
              <Option value="">所有状态</Option>
              <Option value="0">实时发布</Option>
              <Option value="1">定时发布</Option>
            </Select>
          );
        }
        return defaultRender(_);
      },
      valueEnum: {
        0: { text: '实时发布'},
        1: { text: '定时发布'},
      },
    },
    {
      title: '审核状态',
      dataIndex: 'auditStatus',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Select
              showSearch
              optionFilterProp="children"
              style={{ width: 200 }}
              placeholder="请选择"
              onChange={(value) => form.submit()}
            >
              <Option value="">所有状态</Option>
              <Option value="0">待审核</Option>
              <Option value="1">已通过</Option>
              <Option value="2">已拒绝</Option>
            </Select>
          );
        }
        return defaultRender(_);
      },
      valueEnum: {
        0: { text: '待审核', status: 'Processing' },
        1: { text: '已通过', status: 'Success' },
        2: { text: '已拒绝', status: 'Error' },
      },
    },
    {
      title: '标签',
      dataIndex: 'tagIds',
      hideInTable:true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <TagCommonComponent 
              topOrgId = {JSON.parse(localStorage.getItem("user")).topOrgId}
              selectChange={(values) => selectChange(values,form)}>
            </TagCommonComponent>
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '使用设备数',
      dataIndex: 'totalDeviceCount',
      valueType: 'text',
      hideInSearch: true, 
      render: (_, record) => <><span>{record.totalDeviceCount} 台</span></>,
    },
    {
      title: '作者',
      dataIndex: 'userNickname',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '更新时间',
      dataIndex: 'updateDatetime',
      valueType: 'dateTime',
      hideInSearch: true, 
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              record['type'] = 'review';
              setValues(record)
            }}
          >
            {record.auditStatus==0?"预览并审核":"预览"}
          </a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<TableListItem>
        options={false}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        pagination={{ showQuickJumper: true,defaultPageSize: 10 }}
        request={(params, sorter, filter) => planAuditList({ ...params, sorter, filter })}
        columns={columns}
      />
      <PlanReviewModel 
        values={values} 
        approvedLoading={approvedLoading}
        rejectLoading={rejectLoading}
        onApproved={onApproved}
        onReject={onReject}
        onCancel={() => handleModalVisible(false)} 
        modalVisible={createModalVisible}>
        <ProTable<PlanItemParam, PlanItemParam>
      />
      </PlanReviewModel>
    </PageContainer>
  );
};

export default PlanReview;
